﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CoolCode.Web
{
    internal static class RequestExtensions
    {
        //return Utility.ToQueryString<T>(model); 

        /// <summary>
        /// 拼装查询字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string ToQueryString<T>(this T model)
        {
            StringBuilder sb = new StringBuilder();
            if (model != null)
            {
                Type type = model.GetType();
                //遍历所有属性，拼装查询字符串
                type.GetProperties().ForEach(p =>
                {
                    sb.Append(p.Name);
                    sb.Append("=");
                    sb.Append(UrlEncode(p.GetValue(model, null)));
                    sb.Append("&");
                });
                if (sb.Length > 0)
                {
                    //去掉最后一个“&” 
                    return sb.ToString(0, sb.Length - 1);
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// Url编码
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string UrlEncode(object obj)
        {
            if (obj == null)
            {
                return string.Empty;
            }
            else if (obj is DateTime)
            {
                string value = ((DateTime)obj).ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                return System.Web.HttpUtility.UrlEncode(value);
            }
            return System.Web.HttpUtility.UrlEncode(obj.ToString());
        }

    }
}
